<?php
// 应用公共文件

/**
 * 私钥
 */
 $private_key = "-----BEGIN RSA PRIVATE KEY-----
MIICXwIBAAKBgQDXS4jw3uBe/oxgNAjMrMgz8MZJ6hVrfNZubVGqEMxGXhh7x3on
nSw9WXBAfqaACH+B4bsY5jFMhhl2A3DrSvOkitQFKcoUT2vvT1QNOLDiJtj7Ykjz
W1KM6Wd78oGKJ7YjeD/dnQt0HCl8Q7joYAzP8XuCH34ol42qcIXznhn7SQIDAQAB
AoGBAIm5ZEzSBq4+IAaawtZL4XZ4nCBEgpdUMMhLXmZwgHyzTO5B2T7mKJrGUCyx
2EknJooroMh42Sie0ELSSLX8KIb5b7eGBSTl8YO3mLqj4GLBZSAHNLOEJH/fkSb+
cN1H/+BRHWpJ0kXQSTXJDbNBRr/U+VuIo118vO65XAi1QbgBAkEA7skIAm47jYxO
0rfB3GixD5vufb+fJEW0DmcLOv/jrwBWUKBSy0Ief6rrjihWxPeVPDip56YVATsv
MQ9zfg8fiQJBAObQ+SluS1ddesR9s09qd/YxJYkiETYx+SUmdGIRcV2wWkb5erQb
QjO9qs5Pf4/Vylqi9Ff+iHw+65CvITm/TcECQQClQHUNkZIfTKnERK2iRsW6wrRT
TEjrhl2s1f08sJi2pOoXVEzYJAMNYZExSZN7LsiV67UR/qtstbPcJRBNflPZAkEA
3q4/o9v3rdrOxWCsLHMANzFlEC8gwdNmlZPK9o3zfDrWbeDko3wk23whnJcP7zmH
1vedmoNDM/MUGusKuAa7QQJBAIDoioR+E8eeWHlc8IBzFwref105WHCG9WiZp8Cl
sTgu7T5DhSwJpXSzrsV1VNhjxB32zL63m4hnscDurZ07hZE=
-----END RSA PRIVATE KEY-----";

/**
 * 公钥
 */
$public_key = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXS4jw3uBe/oxgNAjMrMgz8MZJ
6hVrfNZubVGqEMxGXhh7x3onnSw9WXBAfqaACH+B4bsY5jFMhhl2A3DrSvOkitQF
KcoUT2vvT1QNOLDiJtj7YkjzW1KM6Wd78oGKJ7YjeD/dnQt0HCl8Q7joYAzP8XuC
H34ol42qcIXznhn7SQIDAQAB
-----END PUBLIC KEY-----";

/**
 * 私钥、公钥加密
 * @param $data
 * @param $type
 * @return string
 */
function sslEn($data,$type='pi'){
    global $private_key,$public_key;
    $encrypted = "";
    if($type == 'pi'){
        //私钥加密
        $pi_key =  openssl_pkey_get_private($private_key);
        openssl_private_encrypt($data,$encrypted,$pi_key);
    }elseif($type == 'pu'){
        //公钥加密
        $pu_key =  openssl_pkey_get_public($public_key);
        openssl_public_encrypt($data,$encrypted,$pu_key);
    }
    $encrypted = base64_encode($encrypted);
    return $encrypted;
}

/**
 * 私钥、公钥解密
 * @param $data
 * @param $type
 * @return string
 */
function sslDe($data,$type='pu'){
    global $private_key,$public_key;
    $decrypted = "";
    if($type=='pu'){
        //公钥解密
        $pu_key = openssl_pkey_get_public($public_key);
        openssl_public_decrypt(base64_decode($data),$decrypted,$pu_key);
    }elseif($type == 'pi'){
        //私钥解密
        $pi_key = openssl_pkey_get_private($private_key);
        openssl_private_decrypt(base64_decode($data),$decrypted,$pi_key);
    }
    return $decrypted;
}

/**
 * 跨域处理
 */

function origin(){
    $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
    $allow_origin = array(
        'http://newmerchant.speeda.cn',
        'http://newbusiness.speeda.cn',
        'http://114.55.60.173',
        'http://a.roy.com'
    );
    if(in_array($origin, $allow_origin)){
        header('Access-Control-Allow-Origin:'.$origin);
    }else{
        die('Invalid Access');
    }
}